<?php
class cmsdream_session {

	private $db = null;
	private $agent = '';
	public function __construct($db) {
		$this->db = $db;
		$this->agent = $_SERVER['HTTP_USER_AGENT'];
	}
	
	public function __destruct() {
		session_write_close();
	}
	
	public function open($save_path, $name) {
		return true;
	}
	
	public function close() {
		return true;
	}
	
	public function read($id) {
		if($this->agent == '' || strlen($this->agent) < 5) {
			echo 'Sorry,Can not support this Agent1.';
			exit();
		}
		$return = '';
		$time = time();
		$this->db->query("DELETE FROM `blog_session` WHERE modified + lifetime < $time");
		if(!!($S = $this->db->fetch("SELECT `data` FROM `blog_session` WHERE sid = '$id' LIMIT 1"))) {
			$return = $S->data;
		}
		return $return;
	}
	
	public function write($id, $data) {
		if($this->agent == '' || strlen($this->agent) < 5) {
			echo 'Sorry,Can not support this Agent2.';
			exit();
		}
		$agent = $this->agent;
		$time = time();
		$ip = self::getClientIp(true);
		$uri = $_SERVER['REQUEST_URI'];
		$host = $_SERVER['SERVER_NAME'];
		$referer = substr($_SERVER['HTTP_REFERER'], 0, 200);
		if($this->db->fetch_field("SELECT COUNT(1) FROM `blog_session` WHERE `sid` = '$id'") == 0) {
			$this->db->query("INSERT INTO `blog_session`(`sid`, `modified`, `lifetime`, `data`, `ip`, `user_agent`, `host`, `request_uri`, `referer`) VALUES('$id', '$time', '1440', '$data', '$ip', '$agent', '$host', '$uri', '$referer')");
		} else {
			$this->db->query("UPDATE `blog_session` SET `modified` = '$time', `data` = '$data', `ip` = '$ip', `user_agent` = '$agent', `host` = '$host', `request_uri` = '$uri', `referer` = '$referer' WHERE `sid` = '$id'");
		}		
		return true;
	}
	
	public function destroy($id) {
		return $this->db->query("DELETE FROM `blog_session` WHERE sid = '$id'");
	}
	
	public function gc($maxlifetime) {
		$time = time();
		return $this->db->query("DELETE FROM `blog_session` WHERE modified + lifetime < $time");
	}

	public static function getClientIp($checkProxy = true) {
		if($checkProxy && $_SERVER['HTTP_CLIENT_IP'] != null) {
			$ip = $_SERVER['HTTP_CLIENT_IP'];
		} else 
			if($checkProxy && $_SERVER['HTTP_X_FORWARDED_FOR'] != null) {
				$ip = $_SERVER['HTTP_X_FORWARDED_FOR'];
			} else {
				$ip = $_SERVER['REMOTE_ADDR'];
			}
		return $ip;
	}
	
}
